<?php

/**
 * 
 * 对接盒子的下载
 * @package  tp5
 * @author   
 */

namespace app\api\controller;

use app\common\controller\Common;
use com\Wave;
use think\Controller;
use think\Db;
use com\SMTP;
use PhpOffice\PhpWord\PhpWord;
use think\Request;
// use think\response\View;
use think\View;

class Downfile extends Common
{
    public $maindir = "/home/wwwroot/default/data/";
    public $speech0 = "";
    public $speech1 = "";
    public $speech2 = "";
    public $userhome = "";
    public $user_id = "";
    public $temp = "";

    public function __construct()
    {
        parent::__construct();
        $this->user_id = 54321;
        $this->temp = $this->maindir . "temp/" . $this->user_id . "";
        $this->speech0 = $this->maindir . "speech0/" . $this->user_id . "";
        $this->speech1 = $this->maindir . "speech1/" . $this->user_id . "";
        $this->speech2 = $this->maindir . "speech2/" . $this->user_id . "";
    }

    public function copy_file_box()
    {
        $dir = '/home/wwwroot/default/ftp/box-recording';
        $files = $this->all_file_box($dir);
        $new_dir = '/home/wwwroot/default/ftp/box-recording';
        if (!is_dir($new_dir)) {
            mkdir($new_dir);
        }
        foreach ($files as $value) {
            // $user_arr = explode('/',$value);
            // $username = $user_arr[5];
            // $this->get_user($username);
            // exit;
            $new_file = $value;
            $pathinfo = pathinfo($value);
            //首先判断该录音文件是否为一个录音文件，如果不是则去合成一个录音文件
            if ($pathinfo['basename']) {
                $f = Db::name('files')->where(array('file_name' => $pathinfo['basename']))->find();
                if (empty($f)) {
                    $arr = explode('/', $value);
                    //$meeting_id = $arr[5] . '-' . $arr[6];
                    //新id如下
                    $meeting_id = $arr[7];

                    $path = $new_file;
                    $wav = $pathinfo['basename'];
                    if ($meeting_id && $path && $wav) {
                        Db::name('files')->insert(array('file_name' => $wav));
                        $u_arr = explode('ftp/', $path);
                        $uid = explode('/', $u_arr[1]);
                        $this->user_id = $uid[1];
                        $this->temp = $this->maindir . "temp/" . $this->user_id . "";
                        $this->speech0 = $this->maindir . "speech0/" . $this->user_id . "";
                        $this->speech1 = $this->maindir . "speech1/box-recording/" . $this->user_id . "";
                        $this->speech2 = $this->maindir . "speech2/" . $this->user_id . "";
                        $this->initdatahome();
                        $this->uploadfile_auto($path, $wav, $meeting_id);
                    }
                }
            }
        }
        //合并文件方法
        $this->file_merge();
    }

    //文件合并逻辑
    public function file_merge()
    {
        //逻辑如下 在meeting_live_speech查找最近2天内的会议(因为查询全部会议没有意义)  找到未转写和正在转写的数据集 获取meeting_id
        $recently2days = [time() - 172800, time()];
        //var_dump($recently2days);
        $map = [
            'create_time' => ['between', $recently2days],
            'transition_state' => ['<>', 2],
            'is_delete' => 0,
            'is_manual' => 1
        ];
        $arr_meeting = DB::name('meeting_live_speech')
            ->where($map)
            ->select();
        //var_dump($arr_meeting);
        //数据为空 就结束
        if (empty($arr_meeting)) {
            return;
        }
        //循环
        foreach ($arr_meeting as $meeting) {
            //如果 meeting_live_speech 的endtime不为0 代表 该会议结束 记录合并文件
            if ($meeting['end_time'] != 0) {
                //查找所有的音频文件  如果全都转写完成合并否则  return
                //全部文件数量
                $all_files_count = DB::name('meeting_speech')
                    ->where(['meeting_id' => $meeting['id']])
                    ->count();
                //已转写文件数量
                $lvsr3_files_count = DB::name('meeting_speech')
                    ->where(['meeting_id' => $meeting['id'], 'lvsr_status' => 3])
                    ->count();
                //数量不一致说明还在转写则不合并
                if ($all_files_count != $lvsr3_files_count) {
                    continue;
                }
                //在meeting_speech查找 meeting_id相等 且 未合并(以lvsr_status == 3 来确定)的数据集  合并则为1
                $speech_arr = DB::name('meeting_speech')
                    ->where(['meeting_id' => $meeting['id'], 'lvsr_status' => 3])
                    ->field('id,device_id,user_id,filename,formatname,seconds,lvsr_data,create_time')
                    //按序号查询
                    ->order('filename asc')
                    ->select();
                if (!$speech_arr) {
                    continue;
                }
                //合并的文件夹
                $path = config('huisheng.file_mp3_path') . "/" . $meeting['uid'] . "/";
                //合并数组中的文件 返回文件名
                $meeting_file = $this->speechFileMerge($speech_arr, $path);
                //如果返回空则continue
                if (!$meeting_file) {
                    continue;
                }
                //记录音频文件的长度
                $seconds = 0;
                foreach ($speech_arr as $value) {
                    if (!$value['seconds']) {
                        continue;
                    }
                    $seconds += $value['seconds'];
                }
                //生成波形图
                if (!is_file($path . $meeting_file . ".json")) {
                    $cmd = "cd " . $path . ";ffmpeg -i " . $meeting_file . ".mp3 " . $meeting_file . ".wav";
                    @exec($cmd);
                    //$this->mkjson($path . $meeting_file . ".wav", $path . $meeting_file . ".json");
                    $file = $path . $meeting_file . ".wav";
                    $sample_count = ceil($seconds * 16000 / 1000);
                    $jsonfile = $path . $meeting_file . ".json";
                    $cmd = "wav2json $file  -s $sample_count -o " . "/home/wwwroot/default/test.json";
                    system($cmd);
                    $ret = file_get_contents("/home/wwwroot/default/test.json");
                    $data = json_decode($ret);
                    foreach ($data->left as $key => $val) {
                        $rt[$key] = $val;
                    }
                    file_put_contents($jsonfile, json_encode($rt));
                    @exec("rm -rf " . $path . $meeting_file . ".wav");
                }
                //获取文件大小方法
                $path = $path . $meeting_file . ".mp3";
                if (file_exists($path)) {
                    $file_size = filesize($path);
                } else {
                    //没有文件返回0
                    $file_size = 0;
                }
                if ($meeting['edit_state']) {
                    //编辑过 记录在线转写的结果
                    $speech_txts = DB::name('meeting_convert')->where(['lid' => $meeting['id']])->field(['transfer', 'editor', 'pcmtime'])->order('sorting asc')->select();
                    $meeting_transfer = $this->onlineTxtMerge($speech_txts);
                    //更新 meeting表
                    DB::name('meeting_live_speech')->where(['id' => $meeting['id']])->update(['size' => $file_size, 'formatname' => $meeting_file, 'seconds' => $seconds, 'transfer' => $meeting_transfer, 'transition_state' => 2, 'update_time' => time()]);
                } else {
                    //未编辑过 记录离线转写的结果
                    $speech_txts = DB::name('meeting_speech')->where(['meeting_id' => $meeting['id'], 'lvsr_status' => 3])->order('filename asc')->field('lvsr_data')->select();
                    $meeting_transfer = $this->offlineTxtMerge($speech_txts, "lvsr_data");
                    //更新 meeting表
                    DB::name('meeting_live_speech')->where(['id' => $meeting['id']])->update(['size' => $file_size, 'formatname' => $meeting_file, 'seconds' => $seconds, 'transfer' => $meeting_transfer, 'transition_state' => 2, 'update_time' => time()]);
                }
            }
            //如果endtime为0 但是最后文件距现在时间已经超过一个小时 则认为会议已经结束
            else if ($meeting['end_time'] == 0) {
                //查找所有的音频文件  如果全都转写完成合并否则  return
                //全部文件数量
                $all_files_count = DB::name('meeting_speech')
                    ->where(['meeting_id' => $meeting['id']])
                    ->count();
                //已转写文件数量
                $lvsr3_files_count = DB::name('meeting_speech')
                    ->where(['meeting_id' => $meeting['id'], 'lvsr_status' => 3])
                    ->count();
                //数量不一致说明还在转写则不合并
                if ($all_files_count != $lvsr3_files_count) {
                    continue;
                }
                //在meeting_speech查找 meeting_id相等 且 未合并(以lvsr_status == 3 来确定)的数据集  合并则为1
                $speech_arr = DB::name('meeting_speech')
                    ->where(['meeting_id' => $meeting['id'], 'lvsr_status' => 3])
                    ->field('id,device_id,user_id,filename,formatname,seconds,lvsr_data,create_time')
                    //按序号查询
                    ->order('filename asc')
                    ->select();
                if (!$speech_arr || $speech_arr[count($speech_arr) - 1]['create_time'] + 60 * 60 >= time()) {
                    continue;
                }
                //合并的文件夹
                $path = config('huisheng.file_mp3_path') . "/" . $meeting['uid'] . "/";
                //合并数组中的文件 返回文件名
                $meeting_file = $this->speechFileMerge($speech_arr, $path);
                //如果返回空则continue
                if (!$meeting_file) {
                    continue;
                }
                //生成波形图
                if (!is_file($path . $meeting_file . ".json")) {
                    $cmd = "cd " . $path . ";ffmpeg -i " . $meeting_file . ".mp3 " . $meeting_file . ".wav";
                    exec($cmd);
                    $file = $path . $meeting_file . ".wav";
                    $sample_count = ceil($seconds * 16000 / 1000);
                    $jsonfile = $path . $meeting_file . ".json";
                    $cmd = "wav2json $file  -s $sample_count -o " . "/home/wwwroot/default/test.json";
                    system($cmd);
                    $ret = file_get_contents("/home/wwwroot/default/test.json");
                    $data = json_decode($ret);
                    foreach ($data->left as $key => $val) {
                        $rt[$key] = $val;
                    }
                    file_put_contents($jsonfile, json_encode($rt));
                    //$this->mkjson($path . $meeting_file . ".wav", $path . $meeting_file . ".json");
                    exec("rm -rf " . $path . $meeting_file . ".wav");
                }
                //记录音频文件的长度
                $seconds = 0;
                foreach ($speech_arr as $value) {
                    if (!$value['seconds']) {
                        continue;
                    }
                    $seconds += $value['seconds'];
                }

                //获取文件大小方法
                $path = $path . $meeting_file . ".mp3";
                if (file_exists($path)) {
                    $file_size = filesize($path);
                } else {
                    //没有文件返回0
                    $file_size = 0;
                }

                if ($meeting['edit_state']) {
                    //编辑过 记录在线转写的结果
                    $speech_txts = DB::name('meeting_convert')->where(['lid' => $meeting['id']])->field(['transfer', 'editor', 'pcmtime'])->order('sorting asc')->select();
                    $meeting_transfer = $this->onlineTxtMerge($speech_txts);
                    //更新 meeting表
                    DB::name('meeting_live_speech')->where(['id' => $meeting['id']])->update(['size' => $file_size, 'formatname' => $meeting_file, 'transfer' => $meeting_transfer, 'seconds' => $seconds, 'transition_state' => 2, 'end_time' => time(), 'update_time' => time()]);
                } else {
                    //未编辑过 记录离线转写的结果
                    $speech_txts = DB::name('meeting_speech')->where(['meeting_id' => $meeting['id'], 'lvsr_status' => 3])->order('filename asc')->field('lvsr_data')->select();

                    $meeting_transfer = $this->offlineTxtMerge($speech_txts, "lvsr_data");
                    //更新 meeting表
                    DB::name('meeting_live_speech')->where(['id' => $meeting['id']])->update(['size' => $file_size, 'formatname' => $meeting_file, 'transfer' => $meeting_transfer, 'seconds' => $seconds, 'transition_state' => 2, 'end_time' => time(), 'update_time' => time()]);
                }
            }
        }
    }

    //合并meeting_id下的转写好的音频文件
    public function speechFileMerge($speech_files_arr, $path)
    {
        //合并后文件名
        $meeting_file = '';
        if (count($speech_files_arr) == 1) {
            //如果只有一个音频文件则合并文件直接等于该音频文件
            $meeting_file = $speech_files_arr[0]['formatname'];
        } else {
            //合并文件命令字符串拼接
            $_files = '';
            //如果多余一个则循环合并
            foreach ($speech_files_arr as $file_value) {
                $formatname = str_replace(".wav", ".mp3", $file_value['formatname']);
                if (is_file($path . $formatname)) {
                    $_files .=  $formatname . "|";
                }
            }
            $meeting_file = trim(date('YmdHis', time()) . rand(1000, 9999) . ".mp3");
            $formatname = substr($_files, 0, -1);
            $cmd = 'cd ' . $path . ' ;ffmpeg -i "concat:' . $formatname . '" -y -acodec copy ' . $meeting_file;
            exec($cmd, $r);
            //删除合并后的文件
            //@unlink($path . "/" . $meeting_file);
        }
        return substr($meeting_file, 0, -4);
    }


    //离线文本 合并
    public function offlineTxtMerge($txts, $lvsr_data)
    {
        $newlist = [];
        $time = 0;
        $consume = 0;
        foreach ($txts as $data_value) {
            $lvsr = isset($data_value[$lvsr_data]) ? json_decode($data_value[$lvsr_data], true) : [];
            if ($lvsr === null) {
                break;
            }
            $consume += $lvsr['consume-time'];
            if (empty($lvsr['list'])) {
                continue;
            }
            foreach ($lvsr['list'] as $key => $time_value) {
                //对文件进行时间的累加
                $time_value_arr = explode("-", $time_value['time']);
                //var_dump($time_value_arr);
                $time_value['time'] = ($time_value_arr[0] + $time) . "-" . ($time_value_arr[1] + $time);
                $newlist[] =  $time_value;
                //如果是最后一个则将$time置为上一段的总时长
                if ($key == count($lvsr['list']) - 1) {
                    $time += $time_value_arr[1];
                }
            }
        }
        $lvsr_data = [
            'consume-time' => $consume,
            'list' => $newlist
        ];
        return json_encode($lvsr_data, JSON_UNESCAPED_UNICODE);
    }

    //在线文本 合并
    public function onlineTxtMerge($list)
    {
        //找到第一个不为空的语音
        $stime = 0;
        $etime = 0;
        $i = 0;
        $json_result_arr = [];
        //合并规则是，找到连续的有字的数据，组合内容，当遇到空格时开始查找，找到最近的不为空格的数据的前一个空格
        //将空格前的所有空格和有字数据合并，记录时间

        //这里剔除转写文件前的空格
        for (; $i < count($list); $i++) {
            if ((!empty($list[$i]['editor']) && $list[$i]['editor'] !== "  ") || (empty($list[$i]['editor']) && $list[$i]['transfer'] !== "  "))
                break;
            $etime += $list[$i]['pcmtime'];
        }

        //
        $convert_str = '';
        for (; $i < count($list); $i++) {
            if ($i == count($list) - 1) {
                $convert_str .= $list[$i]['editor'] ? $list[$i]['editor'] : $list[$i]['transfer'];
                $etime += $list[$i]['pcmtime'];
                //组合函数
                $json_result_arr = $this->toJsonArray($convert_str, $stime, $etime, $json_result_arr);
            }
            if ((!empty($list[$i]['editor']) && $list[$i]['editor'] !== "  ") || (empty($list[$i]['editor']) && $list[$i]['transfer'] !== "  ")) {
                $convert_str .= $list[$i]['editor'] ? $list[$i]['editor'] : $list[$i]['transfer'];
                $etime += $list[$i]['pcmtime'];
            } else if ((!empty($list[$i]['editor']) && $list[$i]['editor'] === "  ") || (empty($list[$i]['editor']) && $list[$i]['transfer'] === "  ")) {
                $etime += $list[$i]['pcmtime'];
                if ((!empty($list[$i + 1]['editor']) && $list[$i + 1]['editor'] !== "  ") || (empty($list[$i + 1]['editor']) && $list[$i + 1]['transfer'] !== "  ")) {
                    //组合函数
                    $json_result_arr = $this->toJsonArray($convert_str, $stime, $etime, $json_result_arr);
                    $convert_str = '';
                    $stime = $etime;
                }
            }
        }
        $data = [
            "consume-time" => $etime,
            "list" => $json_result_arr
        ];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        return $data;
        //var_dump(json_decode($data, true)['list']);
    }


    //将文字，开始结束时间 组合成json字符串
    public function  toJsonArray($convert_str, $stime, $etime, $json_arr)
    {
        $data = [
            "time" => $stime * 5 . "-" . $etime * 5,
            "txt" => $convert_str
        ];
        $json_arr[] = $data;
        return $json_arr;
    }


    public function all_file_box($dir)
    {
        if (is_file($dir)) {
            $pathinfo = pathinfo($dir);
            if ($pathinfo['extension'] == 'md5') {
                // $wav = str_replace('.md5', '.wav', $f);
                $wav = str_replace('.md5', '.wav', $dir);
                if (file_exists($wav)) {
                    if (file_get_contents($dir) == md5_file($wav)) {
                        $this->all[] = $wav;
                    }
                }
            }
            return $this->all;
        }
        if (is_dir($dir)) {
            $open = opendir($dir);
            while (($file = readdir($open)) !== false) {
                if ($file != "." && $file != "..") {
                    $f = $dir . "/" . $file;
                    if (is_file($f)) {
                        $pathinfo = pathinfo($f);
                        if ($pathinfo['extension'] == 'md5') {
                            $wav = str_replace('.md5', '.wav', $f);
                            if (file_exists($wav)) {
                                if (file_get_contents($f) == md5_file($wav)) {
                                    $this->all[] = $wav;
                                }
                            }
                        }
                    } elseif (is_dir($f)) {
                        $this->all_file_box($f);
                    }
                }
            }
        }
        return $this->all;
    }

    public function get_user($username)
    {
        $res = Db::name('admin_user')->where(['username' => $username])->find();
        $this->user_id = $res['id'];
        $this->temp = $this->maindir . "temp/" . $this->user_id . "";
        $this->speech0 = $this->maindir . "speech0/" . $this->user_id . "";
        $this->speech1 = $this->maindir . "speech1/" . $this->user_id . "";
        $this->speech2 = $this->maindir . "speech2/" . $this->user_id . "";
        $this->initdatahome();
    }


    public function uploadfile_auto($path, $wav, $meeting_id)
    {
        $this->initdatahome();
        $temp_dir = $this->temp;
        if (!is_dir($temp_dir)) {
            mkdir($temp_dir, 0777, true);
        }
        if (!$path && !$wav) {
            return json(array('参数错误'));
        }
        // echo "cp $path $temp_dir"."/".$wav;exit;
        system("cp $path $temp_dir" . "/" . $wav);
        $id = $this->createFileFromChunks($wav, $meeting_id);
        $lvsr_type = 1;
        $recorder = Db::name('meeting_speech')->where(array('id' => $id))->find();
        if (empty($recorder)) {
            return json(array('error' => '修改失败'));
        }
        if (!empty($lvsr_type)) {
            $info['update_time'] = time();
            //$info['lvsr_status'] = 1;
            $info['lvsr_type'] = $lvsr_type;
            $r = Db::name('meeting_speech')->where(array('id' => $id))->update($info);
        }

        return $id;
    }


    public function initdatahome()
    {
        if (!is_dir($this->temp)) {
            @mkdir($this->temp, 0777, true);
        }
        if (!is_dir($this->speech0)) {
            @mkdir($this->speech0, 0777, true);
        }
        if (!is_dir($this->speech1)) {
            @mkdir($this->speech1, 0777, true);
        }
        if (!is_dir($this->speech2)) {
            @mkdir($this->speech2, 0777, true);
        }
        // @mkdir($this->temp, 0777, true);
        // @mkdir($this->speech0, 0777, true);
        // @mkdir($this->speech1, 0777, true);
        // @mkdir($this->speech2, 0777, true);
    }

    public function createFileFromChunks($fileName, $meeting_id)
    {

        $id = $this->writerecorderdb($fileName, $meeting_id);

        if ($id) {
            $this->convertformat($fileName, $id);
        } else {
            $data = array('res' => 1, "info" => "存储数据错误");
            return json($data);
        }
        return $id;
    }


    public function writerecorderdb($filename, $meeting_id = 0)
    {
        $where['uid'] = $this->user_id;
        $where['meeting_id'] = $meeting_id;
        $time = time();
        $fileinfo = Db::name('meeting_list')->where($where)->find();
        //这里要进行转写的文件是否编辑的判断，如果修改则不去进行离线转写 即将meeting_speech的lvsr_status置为已转写3，否则不进行设置
        //添加前要把对应meeting_id的所有文件数据的lvsr_status全部修改
        $live_data = DB::name("meeting_live_speech")->where(['meeting_tag' => $meeting_id])->find();
        $lid = $live_data['id'];
        $info['device_id'] = $live_data['did'] ? $live_data['did'] : 0;
        $info['lvsr_start_time'] = $live_data['strat_time'] ? $live_data['strat_time'] : $time;
        if (empty($lid)) {
            //如果没有找到说明出错了，做一些错误处理
        }
        $info['meeting_id'] = $lid ? $lid : $meeting_id;
        $info['lvsr_status'] = $live_data['edit_state'] ? 3 : 1;

        if (!$fileinfo) { //表示没有上传过记录
            $info['filename'] = $filename;
            $info['filenamemd5'] = md5($filename);
            $info['user_id'] = $this->user_id;
            $info['formatname'] = trim(date('YmdHis', time()) . rand(1000, 9999) . "." . substr(strrchr($filename, '.'), 1));
            $info['create_time'] = $time;
            $fileinfo_arr = explode('_', $filename);
            if (count($fileinfo_arr) == 3) {
                $aisle = $fileinfo_arr[1];
            } else {
                $aisle = '99';
            }
            Db::name('meeting_list')->insert(array('meeting_id' => $meeting_id, 'uid' => $this->user_id, 'name' => $meeting_id, 'ctime' => $time, 'stime' => $time, 'etime' => $time, 'statue' => 1, 'all_statue' => 1, 'type' => 1, 'meeting_status' => 3));
            // $recorder_id = Db::name('recorder')->getLastInsID();
            //zp
            //$info['meeting_id'] = $meeting_id;
            $info['aisle'] = $aisle;

            Db::name('meeting_speech')->insert($info);
            $id = Db::name('meeting_speech')->getLastInsID();
            return $id;
        } else { //表示上传记录
            //$subname = date('Ymdhi', $time);
            //$filename = substr($filename, 0, -4) . "_" . $subname . substr($filename, -4);
            $info['filename'] = $filename;
            $info['filenamemd5'] = md5($filename);
            $info['user_id'] = $this->user_id;
            $info['formatname'] = date('YmdHis', time()) . rand(1000, 9999) . "." . substr(strrchr($filename, '.'), 1);
            $info['create_time'] = $time;
            //zp
            //$info['meeting_id'] = $fileinfo['meeting_id'];
            $fileinfo_arr = explode('_', $filename);
            if (count($fileinfo_arr) == 4) {
                $info['aisle'] = $fileinfo_arr[1];
            } else {
                $info['aisle'] = '99';
            }
            Db::name('meeting_speech')->insert($info);
            $id = Db::name('meeting_speech')->getLastInsID();
            return $id;
        }
    }

    public function convertformat($filename, $id)
    {
        $filename = $filename ? $filename : $_GET['filename'];
        $m = Db::name('meeting_speech');
        $where['id'] = $id;
        //$where['filename']=$filename;
        $fileinfo = $m->where($where)->find();
        $pathinfo = pathinfo($filename);
        if ($pathinfo['extension'] == "pcm") {
            $sourcepath = $this->temp . "/" . $filename;
            $pcmpath = $this->speech0 . "/" . $fileinfo['formatname'];
            rename($sourcepath, $pcmpath);
            $wavpath = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".wav";
            system("sox -t raw -c 1 -s -b 16 -r 16000  $pcmpath -c 1 -s -r 16000 $wavpath", $return);
        } else if ($pathinfo['extension'] == "wav") {
            $sourcepath = $this->temp . "/" . $filename;
            $pcmpath = $this->speech0 . "/" . $fileinfo['formatname'];
            rename($sourcepath, $pcmpath);
            $wavpath = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".wav";
            // dump($wavpath);exit;
            copy($pcmpath, $wavpath);
        } else if ($pathinfo['extension'] == "mp3") {
            $sourcepath = $this->temp . "/" . $filename;
            $pcmpath = $this->speech0 . "/" . $fileinfo['formatname'];
            rename($sourcepath, $pcmpath);
            $wavpatht = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . "_t.wav";
            $wavpath = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".wav";
            system("lame --mp3input --decode -m m --resample 16 " . $pcmpath . " " . $wavpatht, $return);
            system("sox " . $wavpatht . " -r 16000 -c 1 " . $wavpath, $return);
        }
        $mp3path = $this->speech2 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".mp3";
        //echo "ffmpeg -f s16le -ar 16000 -ac 1 -i '" . $wavpath . "' " . $mp3path; 
        //system("lame  --quiet -b 32 --resample 11  " . $wavpath . " " . $mp3path, $return);
        system("ffmpeg -f s16le -ar 16000 -ac 1 -i '" . $wavpath . "' " . $mp3path);
        // $Mkmp=new Mkwavejson($mp3path);
        // $json=$Mkmp->mkjson();
        // file_put_contents(substr($mp3path,0,-3)."json",$json);
        $wavinfo = $this->mkjson($wavpath, substr($mp3path, 0, -3) . "json");
        $result['msg'] = "0";
        if ($fileinfo['lvsr_status'] == 3) { //表示已经转写
            //$info['seconds']=$wavinfo['seconds'];
            $info['seconds'] = $wavinfo['seconds'];
            $info['Channels'] = $wavinfo['Channels'];
            $info['SamplesPerSec'] = $wavinfo['SamplesPerSec'];
            $info['AvgBytesPerSec'] = $wavinfo['AvgBytesPerSec'];
            $info['BitsPerSample'] = $wavinfo['BitsPerSample'];
            $m->where($where)->update($info);
        } else {
            $task = "recorder_lvsr";
            $a['path'] = $wavpath;
            $a['id'] = $fileinfo['_id'];
            $info['lvsr_status'] = 1;
            //$info['seconds']=$wavinfo['seconds'];
            $info['seconds'] = $wavinfo['seconds'];
            $info['Channels'] = $wavinfo['Channels'];
            $info['SamplesPerSec'] = $wavinfo['SamplesPerSec'];
            $info['AvgBytesPerSec'] = $wavinfo['AvgBytesPerSec'];
            $info['BitsPerSample'] = $wavinfo['BitsPerSample'];
            $m->where($where)->update($info);
        }
        // $this->assign('list',$list);
        //echo json_encode($result);
        // exit;
    }


    public function mkjson($file, $jsonfile)
    {
        $Mkmp = new Wave($file);
        $a = $Mkmp->wavechunk();
        $sample_count = ceil($a['seconds'] * $a['SamplesPerSec'] / 1000);
        $cmd = "wav2json $file  -s $sample_count -o " . "/home/wwwroot/default/test.json";
        //echo $cmd;exit;
        system($cmd);
        $ret = file_get_contents("/home/wwwroot/default/test.json");
        $data = json_decode($ret);
        foreach ($data->left as $key => $val) {
            $rt[$key] = $val;
        }
        file_put_contents($jsonfile, json_encode($rt));
        return $a;
    }



    public function speech_detail()
    {
        $data['url'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        // dump($data['url']);exit;
        $file_name = input('file_name');
        if (!$file_name) {
            return json(array('error' => '文件名不能为空'), 401);
        }
        $addr = input('address');
        if (!$addr) {
            return json(array('error' => '地址为空'), 402);
        }
        //$meeting_id = $addr . '-' . $file_name;
        $res = Db::name('meeting_live_speech')->where(['filename' => $file_name])->find();
        if (!$res) {
            $data['msg'] = '文件未找到';
            $this->assign("data", $data);
            return View('error');
        }
        $post_time = input('post_time');
        if (!$post_time) {
            $data['msg'] = '参数缺失';
            $this->assign("data", $data);
            return View('error');
        }
        $token = input('token');
        $check_arr = $addr . $post_time . 'Imsl.8632+Bkrs';
        $check_md5 = md5($check_arr);
        if ($token != $check_md5) {
            $data['msg'] = '非法链接';
            $this->assign("data", $data);
            return View('error');
        }
        /*  if($res['post_time'] == $post_time){
            if(time() - $res['write_time'] > 7200){
                $data['msg'] = '链接已失效';
                $this->assign("data",$data);
                return View('error');
            }
        }else{
            $data['post_time'] = $post_time;
            $data['write_time'] = time();
            Db::name('meeting_list')->where(['meeting_id'=>$meeting_id])->update($data);
        } */
        //$list = Db::name('meeting_speech')->where(['meeting_id' => $meeting_id])->select();
        //$num = array();
        // foreach ($list as $key => $value) {
        //     $num[] = $key;
        // }
        //$total_do = Db::name('meeting_speech')->where(['meeting_id' => $meeting_id, 'lvsr_status' => 3])->count();
        // $arr = explode('-',$res['meeting_id']);
        // $data['name']  = $arr['1'];
        $data['name']  = $file_name;
        $data['id']  = $res['id'];
        $data['time'] = date('Y-m-d H:i:s', $res['create_time']);
        //$total = count($list);
        //$data['total'] = $total;
        //$data['total_do'] = $total_do;
        if ($res['transition_state'] == 2) {
            $data['status'] = '已完成';
        } else {
            $data['status'] = '转写中';
        }
        $this->assign("data", $data);
        $this->assign("num", $res);
        return View('down');
    }


    public function download_result_detail()
    {
        $id = input('param.id');
        if (!$id) {
            return json(array(), 404);
        }
        $res = Db::name('meeting_live_speech')->where(array('id' => $id))->find();
        $s = $res;
        $type = input('type/s');
        if ($type == 'mp3') {
            $file = "/home/wwwroot/default/data/speech2/" . $s['uid'] . "/" . $s['formatname'] . ".mp3";
        } else if ($type == 'docx') {
            $lvsr = empty($s['editor']) ? json_decode($s['transfer'], 1) : json_decode($s['editor'], 1);
            if (!empty($lvsr['list'])) {
                $num1 = array();
                foreach ($lvsr['list'] as $key => $row) {
                    $arr2 = explode('-', $row['time']);
                    $num1[$key] = $arr2[0];
                }
                array_multisort($num1, SORT_ASC, $lvsr['list']);
                $arr = array();
                foreach ($lvsr['list'] as $k => $l) {
                    $arr[$k]['time'] = $l['time'];
                    $arr[$k]['txt'] = $l['txt'];
                }
            }

            //修改转写结果格式，按照句号分段，首行缩进。对应<br/>和&nbsp;
            $lvsr_txt = '';
            foreach ($lvsr['list'] as $k => $v) {
                $lvsr_txt .= $v['txt'];
                if ($k == 0 && mb_substr($lvsr['list'][$k]['txt'], 0, 4, 'utf-8') != '<br>') {
                    $lvsr['list'][$k]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k]['txt'];
                }
                //var_dump(mb_substr($v['txt'], -1,1, 'utf-8') == '。');
                //die;
                if (mb_substr($v['txt'], -1, 1, 'utf-8') == '。' && mb_substr($lvsr['list'][$k + 1]['txt'], 0, 4, 'utf-8') != '<br>') {
                    $lvsr['list'][$k + 1]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k + 1]['txt'];
                }
            }
            //phpword转格式
            $phpWord = new PhpWord();
            $template = config('huisheng.word_template');
            $document = $phpWord->loadTemplate($template);
            $document->setValue('Value1', '');
            $document->setValue('Value2', date('Y年m月d日 h时i分m秒', $res['start_time']));
            $document->setValue('Value3', '');
            $document->setValue('Value4', '');
            $document->setValue('Value5', '');
            $document->setValue('Value6', $lvsr_txt);
            $document->setValue('Value7', '');
            $docx_path = config('huisheng.word_result') . $s['formatname'] . ".docx";
            $document->saveAs($docx_path);
            $file = $docx_path;


            // file_put_contents('/home/wwwroot/default/data/speech2/text.json', '');
            // file_put_contents('/home/wwwroot/default/data/speech2/text_oral.json', '');
            // file_put_contents('/home/wwwroot/default/data/speech2/text.json', json_encode($arr));
            // system('python2 /data/disc1/asr/am-training/s8/deal_oral.py /home/wwwroot/default/data/speech2/text.json /home/wwwroot/default/data/speech2/text_oral.json');
            // // $json = "/home/wwwroot/default/data/speech2/text.json";
            // // file_put_contents($json,json_encode($arr));
            // $docx = "/home/wwwroot/default/data/speech2/" . $s['user_id'] . "/" . substr($s['formatname'], 0, -3) . "docx";
            // if (file_exists($docx)) {
            //     unlink($docx);
            // }
            // if (!file_exists($docx)) {
            //     $url = "php /home/wwwroot/default/phpWord/samples/word.php $docx ";
            //     system($url);
            // }
            // $file = $docx;
        }
        // else if($type == 'pdf') {
        //     $lvsr = isset($s['lvsr_data_current']) ? json_decode($s['lvsr_data_current'], 1) : json_decode($s['lvsr_data'], 1);
        //     if (!empty($lvsr['list'])) {
        //         $num1 = array();
        //         foreach ($lvsr['list'] as $key => $row) {
        //             $arr2 = explode('-', $row['time']);
        //             $num1[$key] = $arr2[0];
        //         }
        //         array_multisort($num1, SORT_ASC, $lvsr['list']);
        //         $arr = array();
        //         foreach ($lvsr['list'] as $k => $l) {
        //             $arr[$k]['time'] = $l['time'];
        //             $arr[$k]['txt'] = $l['txt'];
        //         }
        //     }

        //     //修改转写结果格式，按照句号分段，首行缩进。对应<br/>和&nbsp;
        //     $lvsr_txt = '';
        //     foreach ($lvsr['list'] as $k => $v) {
        //         $lvsr_txt .= $v['txt'];
        //         if ($k == 0 && mb_substr($lvsr['list'][$k]['txt'], 0, 4, 'utf-8') != '<br>') {
        //             $lvsr['list'][$k]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k]['txt'];
        //         }
        //         //var_dump(mb_substr($v['txt'], -1,1, 'utf-8') == '。');
        //         //die;
        //         if (mb_substr($v['txt'], -1, 1, 'utf-8') == '。' && mb_substr($lvsr['list'][$k + 1]['txt'], 0, 4, 'utf-8') != '<br>') {
        //             $lvsr['list'][$k + 1]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k + 1]['txt'];
        //         }
        //     }
        //     //dompdf转格式
        //     $dompdf = new \Dompdf\Dompdf();
        //     //Generate HTML content
        //     $html = file_get_contents(ROOT_PATH . 'public/results/table.html');
        //     $dompdf->loadHtml($html);
        //     //Setup the paper size and orientation
        //     $dompdf->setPaper('A4', 'portrait');
        //     //Render the HTML as PDF
        //     $dompdf->render();
        //     //Output the generated PDF to Browser
        //     $pdfname = '中文abc';
        //     $dompdf->stream($pdfname);
        // }
        //var_dump($file);exit;
        download_result_one($file);
    }


    public function download_result()
    {
        $id = input('id/s');
        if (!$id) {
            return json(array(), 404);
        }
        // $index = input('index/d',0);
        // $recorder = Db::name('meeting_list')->where(array('meeting_id' => $id))->find();
        // if (!$recorder) {
        //     return json(array(), 404);
        // }
        $speech = Db::name('meeting_live_speech')->where(array('id' => $id))->find();
        // dump($speech);exit;
        // foreach ($speech as $s) {
        $zip_file = "/home/wwwroot/default/data/public/result/" . $speech['formatname'] . '.zip';
        if (file_exists($zip_file)) {
            unlink($zip_file);
        }
        // $p = path_info($s['filename']);
        // $channels = explode('_', $p['filename']);
        // // dump($channels);
        // if ($channels[1] == '00') {
        //     $filename = 'all';
        // } else {
        //     // $filename = 'channel_'.$channels[1].'_'.$channels[2];
        //     $filename = 'channel_' . $channels[0];
        // }
        //var_dump($filename);
        //continue;//exit;
        $files['mp3'][] = "/home/wwwroot/default/data/speech2/" . $speech['uid'] . "/" . $speech['formatname'] . ".mp3";
        // $lvsr = empty($speech['editor']) ? json_decode($speech['transfer'], 1) : json_decode($speech['editor'], 1);
        // // $txt_content = '';
        // if (!empty($lvsr['list'])) {
        //     $num1 = array();
        //     foreach ($lvsr['list'] as $key => $row) {
        //         $arr2 = explode('-', $row['time']);
        //         $num1[$key] = $arr2[0];
        //     }
        //     array_multisort($num1, SORT_ASC, $lvsr['list']);
        //     $arr = array();
        //     foreach ($lvsr['list'] as $k => $l) {
        //         // $txt_content.=$l['txt'];
        //         $arr[$k]['time'] = $l['time'];
        //         $arr[$k]['txt'] = $l['txt'];
        //     }
        // }
        // file_put_contents('/home/wwwroot/default/data/speech2/text.json', '');
        // file_put_contents('/home/wwwroot/default/data/speech2/text_oral.json', '');
        // file_put_contents('/home/wwwroot/default/data/speech2/text.json', json_encode($arr));
        // system('python2 /data/disc1/asr/am-training/s8/deal_oral.py /home/wwwroot/default/data/speech2/text.json /home/wwwroot/default/data/speech2/text_oral.json');
        // $json = "/home/wwwroot/default/data/speech2/text.json";
        // file_put_contents($json,json_encode($arr));
        $lvsr = empty($speech['editor']) ? json_decode($speech['transfer'], 1) : json_decode($speech['editor'], 1);
        if (!empty($lvsr['list'])) {
            $num1 = array();
            foreach ($lvsr['list'] as $key => $row) {
                $arr2 = explode('-', $row['time']);
                $num1[$key] = $arr2[0];
            }
            array_multisort($num1, SORT_ASC, $lvsr['list']);
            $arr = array();
            foreach ($lvsr['list'] as $k => $l) {
                $arr[$k]['time'] = $l['time'];
                $arr[$k]['txt'] = $l['txt'];
            }
        }

        //修改转写结果格式，按照句号分段，首行缩进。对应<br/>和&nbsp;
        $lvsr_txt = '';
        foreach ($lvsr['list'] as $k => $v) {
            $lvsr_txt .= $v['txt'];
            if ($k == 0 && mb_substr($lvsr['list'][$k]['txt'], 0, 4, 'utf-8') != '<br>') {
                $lvsr['list'][$k]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k]['txt'];
            }
            //var_dump(mb_substr($v['txt'], -1,1, 'utf-8') == '。');
            //die;
            if (mb_substr($v['txt'], -1, 1, 'utf-8') == '。' && mb_substr($lvsr['list'][$k + 1]['txt'], 0, 4, 'utf-8') != '<br>') {
                $lvsr['list'][$k + 1]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k + 1]['txt'];
            }
        }
        //phpword转格式
        $phpWord = new PhpWord();
        $template = config('huisheng.word_template');
        $document = $phpWord->loadTemplate($template);
        $document->setValue('Value1', '');
        $document->setValue('Value2', date('Y年m月d日 h时i分m秒', $speech['start_time']));
        $document->setValue('Value3', '');
        $document->setValue('Value4', '');
        $document->setValue('Value5', '');
        $document->setValue('Value6', $lvsr_txt);
        $document->setValue('Value7', '');
        $docx_path = config('huisheng.word_result') . $speech['formatname'] . ".docx";
        $document->saveAs($docx_path);
        //$file = $docx_path;

        // $docx = "/home/wwwroot/default/data/speech2/" . $s['user_id'] . "/" . substr($s['formatname'], 0, -3) . "docx";
        // if (file_exists($docx)) {
        //     unlink($docx);
        // }
        // if (!file_exists($docx)) {
        //     $url = "php '/home/wwwroot/default/phpWord/samples/word.php' $docx ";
        //     system($url);
        // }
        $files['names'] = $speech['filename'];
        $files['docx'][] = $docx_path;
        // }
        // $readme = "/home/wwwroot/default/data/speech2/" . $s['user_id'] . "/" . $recorder['name'] . "-会议说明.txt";
        // if (!file_exists($readme)) {
        //     file_put_contents($readme, '时间：' . date('Y-m-d H:i', $recorder['ctime']) . "\r\n" . "会议名称：" . $recorder['name'] . "\r\n" . "会议简介：" . $recorder['desc']);
        // }
        //$files['readme'][] = '';
        //  dump($zip_file);
        //  dump($files);
        //  exit;
        download_result_e($zip_file, $files);
        exit;
    }

    public function downloadSpeechAndContent()
    {
        $id = input('param.id');
        if (!$id) {
            return json(array(), 404);
        }
        $res = Db::name('meeting_live_speech')->where(array('id' => $id))->find();
        $s = $res;
        $type = input('type/s');
        if ($type == 'mp3') {
            $file = $res['is_manual'] == 1 ? "/home/wwwroot/default/data/speech2/" . $s['uid'] . "/" . $s['formatname'] . ".mp3" : "/home/wwwroot/default/data/speech3/" . $s['uid'] . "/" . $s['formatname'] . ".mp3";
        } else if ($type == 'docx') {
            $lvsr = empty($s['editor']) ? json_decode($s['transfer'], 1) : json_decode($s['editor'], 1);
            if (!empty($lvsr['list'])) {
                $num1 = array();
                foreach ($lvsr['list'] as $key => $row) {
                    $arr2 = explode('-', $row['time']);
                    $num1[$key] = $arr2[0];
                }
                array_multisort($num1, SORT_ASC, $lvsr['list']);
                $arr = array();
                foreach ($lvsr['list'] as $k => $l) {
                    $arr[$k]['time'] = $l['time'];
                    $arr[$k]['txt'] = $l['txt'];
                }
            }

            //修改转写结果格式，按照句号分段，首行缩进。对应<br/>和&nbsp;
            $lvsr_txt = '';
            foreach ($lvsr['list'] as $k => $v) {
                $lvsr_txt .= $v['txt'];
                if ($k == 0 && mb_substr($lvsr['list'][$k]['txt'], 0, 4, 'utf-8') != '<br>') {
                    $lvsr['list'][$k]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k]['txt'];
                }
                //var_dump(mb_substr($v['txt'], -1,1, 'utf-8') == '。');
                //die;
                if (mb_substr($v['txt'], -1, 1, 'utf-8') == '。' && mb_substr($lvsr['list'][$k + 1]['txt'], 0, 4, 'utf-8') != '<br>') {
                    $lvsr['list'][$k + 1]['txt'] = '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $lvsr['list'][$k + 1]['txt'];
                }
            }
            //phpword转格式
            $phpWord = new PhpWord();
            $template = config('share_path') . config('huisheng.word_template');
            $document = $phpWord->loadTemplate($template);
            $document->setValue('Value1', '');
            $document->setValue('Value2', date('Y年m月d日 h时i分m秒', $res['start_time']));
            $document->setValue('Value3', '');
            $document->setValue('Value4', '');
            $document->setValue('Value5', '');
            $document->setValue('Value6', $lvsr_txt);
            $document->setValue('Value7', '');
            $docx_path = config('huisheng.word_result') . $s['formatname'] . ".docx";
            $document->saveAs($docx_path);
            $file = $docx_path;
        }
        download_result_one($file);
    }


    public function send_email()
    {
        // require_once "../cSmtp.php";
        //******************** 配置信息 ********************************
        $title = input('title');
        $content = input('url');
        $to_email = input('mail/s');
        $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
        if (!preg_match($pattern, $to_email)) {
            $data['msg'] = '请输入正确邮箱';
            $this->assign("data", $data);
            return View('error');
        }
        //$smtpserver = "smtp.163.com";//SMTP服务器
        $smtpserver = "smtp.raisound.com"; //SMTP服务器
        $smtpserverport = 25; //SMTP服务器端口
        $smtpusermail = "asrupload@raisound.com"; //SMTP服务器的用户邮箱
        $smtpemailto = $to_email; //发送给谁
        $smtpuser = "asrupload@raisound.com"; //SMTP服务器的用户帐号，注：部分邮箱只需@前面的用户名
        $smtppass = "86329312"; //SMTP服务器的授权码
        $mailtitle = $title; //邮件主题
        $mailcontent = "<a href=" . $content . ">" . $content . '</a>'; //邮件内容
        $mailtype = "HTML"; //邮件格式（HTML/TXT）,TXT为文本邮件
        //************************ 配置信息 ****************************
        $smtp = new SMTP($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //这里面的一个true是表示使用身份验证,否则不使用身份验证.
        $smtp->debug = FALSE; //是否显示发送的调试信息
        $state = $smtp->sendmail($smtpemailto, $smtpusermail, $mailtitle, $mailcontent, $mailtype);
        if ($state == "") {
            $data['msg'] = '对不起，邮件发送失败！请检查邮箱填写是否有误。';
            $this->assign("data", $data);
            return View('error');
        }
        $data['msg'] = '发送成功,请注意查收';
        $this->assign("data", $data);
        return View('error');
    }
}
